<?php
if (PHP_SAPI != 'cli') exit('CLI only');
if (!is_file('./servers.db')) exit('Servers database not found. Make sure that servers.db exists');

$db = new SQLite3('./servers.db');

function prompt($text, $num = FALSE)
{
    echo $text;
    $input = trim(fgets(STDIN));

    if ($num AND !ctype_digit($input)) exit('Invalid input (num required)');

    return $input;
}

$name = prompt('Please enter your server name: ');
$ip = prompt('Please enter your server IP: ');
$port = prompt('Please enter your server port: ', TRUE);
$password = prompt('Please enter your server password: ');
$logURL = prompt('Please enter log URL: ');

if (!preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/i', $ip))
{
    exit('Invalid IP');
}

$name = SQLite3::escapeString($name);
$ip = SQLite3::escapeString($ip);
$port = (int) $port;
$password = SQLite3::escapeString($password);
$logURL = SQLite3::escapeString($logURL);

$db->query("INSERT INTO servers (name, ip, port, password, game, log_url) VALUES ('$name', '$ip', $port, '$password', 'blackops', '$logURL')");

exit('Server has been sucessfully created. ID: '.$db->lastInsertRowID());

$db->close();